package com.zhz.common.shiro.realm;

import com.beust.jcommander.internal.Sets;
import com.zhz.common.shiro.entity.UserProfileResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Objects;
import java.util.Set;

//公共的realm：获取安全数据，构造权限信息
public class IhrmRealm extends AuthorizingRealm {

    public void setName(String name) {
        super.setName("ihrmRealm");
    }

    /**
     * 授权方法
     *
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取安全数据
        UserProfileResponse result = (UserProfileResponse) principalCollection.getPrimaryPrincipal();
        //2.获取权限信息
        UserProfileResponse.RoleInfo roles = result.getRoles();
        Set<String> apis = Sets.newHashSet();
        if (Objects.nonNull(roles)) {
            apis = roles.getApis();
        }
        //3.构造权限数据，返回值
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(apis);
        return info;
    }

    /**
     * 认证方法
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }
}
